//
//  CZNetWorktool.swift
//  1215微博终极项目
//
//  Created by chok崋 on 15/12/17.
//  Copyright © 2015年 周卓华. All rights reserved.
//

import UIKit
import AFNetworking
class CZNetWorktool: AFHTTPSessionManager {
    
    //单例
//    static let sharedNetWorkTool :CZNetWorktool = {
//        let baseURL = NSURL(string: "https://api.weibo.com/")!
//        
//        let tool = CZNetWorktool(baseURL: baseURL)
//        return tool
//    }()
    
    private init()
    {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        //在构造函数里面，子类不能调用父类的便利构造函数，只能调用指定的构造函数
        super.init(baseURL: baseURL, sessionConfiguration: nil)
        
        //设置响应的序列化支持,支持text/plain
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置默认调用单例的构造方法
    static let CZNetWorkInstance:CZNetWorktool = CZNetWorktool()
    
    //设置授权相关的信息
    private let client_id = "783061668"
     let redirect_uri = "http://www.baidu.com/"
    
    //拼接URL的地址，返回NSURL
    func oauthURL() ->NSURL
    {
         let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!
    }
    
    //定义post请求的参数
    private let client_secret = "6362f4233fd98a376545d0116a3c7306"
    private let grant_type = "authorization_code"
    
    //获取accestoken(post方法)
    //当网络请求成功的时候需要，请求闭包进行回调
    func loadAcessToken(code:String, finished:(result:[String:AnyObject]?,error:NSError? )-> ())
    {
         //url地址
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        //post请求所用到的参数
        let parameters = [
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":grant_type,
            "code":code,
            "redirect_uri":redirect_uri
        ]
        
        //post请求
        POST(urlStr, parameters: parameters, success: { (_, result) -> Void in
            
            print("result:\(result)")
            //把请求的结果强制转换成字典
            let dict = result as! [String:AnyObject]
            finished(result: dict, error: nil)
            
            }) { (_, error) -> Void in
                print("error:\(error)")
                finished(result: nil, error: error)
        }
    }
}














